<?php

/**
 * CatalogApi
 * PHP version 8.3.
 *
 * @category Class
 *
 * @author   OpenAPI Generator team
 *
 * @see     https://openapi-generator.tech
 */

/**
 * Selling Partner API for Catalog Items.
 *
 * Use the Selling Partner API for Catalog Items to retrieve information about items in the Amazon catalog.  For more information, refer to the [Catalog Items API Use Case Guide](https://developer-docs.amazon.com/sp-api/docs/:catalog-items-api-v2022-04-01-use-case-guide).
 *
 * The version of the OpenAPI document: 2022-04-01
 * Generated by: https://openapi-generator.tech
 * Generator version: 7.9.0
 */

/**
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

namespace SpApi\Api\catalogItems\v2022_04_01;

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use SpApi\ApiException;
use SpApi\AuthAndAuth\RestrictedDataTokenSigner;
use SpApi\Configuration;
use SpApi\HeaderSelector;
use SpApi\Model\catalogItems\v2022_04_01\Item;
use SpApi\Model\catalogItems\v2022_04_01\ItemSearchResults;
use SpApi\ObjectSerializer;
use Symfony\Component\RateLimiter\LimiterInterface;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\RateLimiter\Storage\InMemoryStorage;

/**
 * CatalogApi Class Doc Comment.
 *
 * @category Class
 *
 * @author   OpenAPI Generator team
 *
 * @see     https://openapi-generator.tech
 */
class CatalogApi
{
    public ?LimiterInterface $getCatalogItemRateLimiter;
    public ?LimiterInterface $searchCatalogItemsRateLimiter;
    protected ClientInterface $client;

    protected Configuration $config;

    protected HeaderSelector $headerSelector;

    /**
     * @var int Host index
     */
    protected int $hostIndex;

    private bool $rateLimiterEnabled;
    private InMemoryStorage $rateLimitStorage;

    /**
     * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec
     */
    public function __construct(
        Configuration $config,
        ?ClientInterface $client = null,
        ?bool $rateLimiterEnabled = true,
        ?HeaderSelector $selector = null,
        int $hostIndex = 0
    ) {
        $this->config = $config;
        $this->rateLimiterEnabled = $rateLimiterEnabled;

        if ($rateLimiterEnabled) {
            $this->rateLimitStorage = new InMemoryStorage();

            $factory = new RateLimiterFactory(Configuration::getRateLimitOptions('CatalogApi-getCatalogItem'), $this->rateLimitStorage);
            $this->getCatalogItemRateLimiter = $factory->create('CatalogApi-getCatalogItem');
            $factory = new RateLimiterFactory(Configuration::getRateLimitOptions('CatalogApi-searchCatalogItems'), $this->rateLimitStorage);
            $this->searchCatalogItemsRateLimiter = $factory->create('CatalogApi-searchCatalogItems');
        }

        $this->client = $client ?: new Client();
        $this->headerSelector = $selector ?: new HeaderSelector();
        $this->hostIndex = $hostIndex;
    }

    /**
     * Set the host index.
     *
     * @param int $hostIndex Host index (required)
     */
    public function setHostIndex(int $hostIndex): void
    {
        $this->hostIndex = $hostIndex;
    }

    /**
     * Get the host index.
     *
     * @return int Host index
     */
    public function getHostIndex(): int
    {
        return $this->hostIndex;
    }

    public function getConfig(): Configuration
    {
        return $this->config;
    }

    /**
     * Operation getCatalogItem.
     *
     * @param string        $asin
     *                                           The Amazon Standard Identification Number (ASIN) of the item. (required)
     * @param string[]      $marketplace_ids
     *                                           A comma-delimited list of Amazon marketplace identifiers. To find the ID for your marketplace, refer to [Marketplace IDs](https://developer-docs.amazon.com/sp-api/docs/marketplace-ids). (required)
     * @param null|string[] $included_data
     *                                           A comma-delimited list of datasets to include in the response. (optional)
     * @param null|string   $locale
     *                                           The locale for which you want to retrieve localized summaries. Defaults to the primary locale of the marketplace. (optional)
     * @param null|string   $restrictedDataToken Restricted Data Token (RDT) for accessing restricted resources (optional, required for operations that return PII)
     *
     * @throws ApiException              on non-2xx response
     * @throws \InvalidArgumentException
     */
    public function getCatalogItem(
        string $asin,
        array $marketplace_ids,
        ?array $included_data = null,
        ?string $locale = null,
        ?string $restrictedDataToken = null
    ): Item {
        list($response) = $this->getCatalogItemWithHttpInfo($asin, $marketplace_ids, $included_data, $locale, $restrictedDataToken);

        return $response;
    }

    /**
     * Operation getCatalogItemWithHttpInfo.
     *
     * @param string        $asin
     *                                           The Amazon Standard Identification Number (ASIN) of the item. (required)
     * @param string[]      $marketplace_ids
     *                                           A comma-delimited list of Amazon marketplace identifiers. To find the ID for your marketplace, refer to [Marketplace IDs](https://developer-docs.amazon.com/sp-api/docs/marketplace-ids). (required)
     * @param null|string[] $included_data
     *                                           A comma-delimited list of datasets to include in the response. (optional)
     * @param null|string   $locale
     *                                           The locale for which you want to retrieve localized summaries. Defaults to the primary locale of the marketplace. (optional)
     * @param null|string   $restrictedDataToken Restricted Data Token (RDT) for accessing restricted resources (optional, required for operations that return PII)
     *
     * @return array of \SpApi\Model\catalogItems\v2022_04_01\Item, HTTP status code, HTTP response headers (array of strings)
     *
     * @throws ApiException              on non-2xx response
     * @throws \InvalidArgumentException
     */
    public function getCatalogItemWithHttpInfo(
        string $asin,
        array $marketplace_ids,
        ?array $included_data = null,
        ?string $locale = null,
        ?string $restrictedDataToken = null
    ): array {
        $request = $this->getCatalogItemRequest($asin, $marketplace_ids, $included_data, $locale);
        if (null !== $restrictedDataToken) {
            $request = RestrictedDataTokenSigner::sign($request, $restrictedDataToken, 'CatalogApi-getCatalogItem');
        } else {
            $request = $this->config->sign($request);
        }

        try {
            $options = $this->createHttpClientOption();

            try {
                if ($this->rateLimiterEnabled) {
                    $this->getCatalogItemRateLimiter->consume()->ensureAccepted();
                }
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getResponse()->getBody()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }
            if ('\SpApi\Model\catalogItems\v2022_04_01\Item' === '\SplFileObject') {
                $content = $response->getBody(); // stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ('\SpApi\Model\catalogItems\v2022_04_01\Item' !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, '\SpApi\Model\catalogItems\v2022_04_01\Item', []),
                $response->getStatusCode(),
                $response->getHeaders(),
            ];
        } catch (ApiException $e) {
            $data = ObjectSerializer::deserialize(
                $e->getResponseBody(),
                '\SpApi\Model\catalogItems\v2022_04_01\ErrorList',
                $e->getResponseHeaders()
            );
            $e->setResponseObject($data);

            throw $e;
        }
    }

    /**
     * Operation getCatalogItemAsync.
     *
     * @param string        $asin
     *                                       The Amazon Standard Identification Number (ASIN) of the item. (required)
     * @param string[]      $marketplace_ids
     *                                       A comma-delimited list of Amazon marketplace identifiers. To find the ID for your marketplace, refer to [Marketplace IDs](https://developer-docs.amazon.com/sp-api/docs/marketplace-ids). (required)
     * @param null|string[] $included_data
     *                                       A comma-delimited list of datasets to include in the response. (optional)
     * @param null|string   $locale
     *                                       The locale for which you want to retrieve localized summaries. Defaults to the primary locale of the marketplace. (optional)
     *
     * @throws \InvalidArgumentException
     */
    public function getCatalogItemAsync(
        string $asin,
        array $marketplace_ids,
        ?array $included_data = null,
        ?string $locale = null
    ): PromiseInterface {
        return $this->getCatalogItemAsyncWithHttpInfo($asin, $marketplace_ids, $included_data, $locale)
            ->then(
                function ($response) {
                    return $response[0];
                }
            )
        ;
    }

    /**
     * Operation getCatalogItemAsyncWithHttpInfo.
     *
     * @param string        $asin
     *                                       The Amazon Standard Identification Number (ASIN) of the item. (required)
     * @param string[]      $marketplace_ids
     *                                       A comma-delimited list of Amazon marketplace identifiers. To find the ID for your marketplace, refer to [Marketplace IDs](https://developer-docs.amazon.com/sp-api/docs/marketplace-ids). (required)
     * @param null|string[] $included_data
     *                                       A comma-delimited list of datasets to include in the response. (optional)
     * @param null|string   $locale
     *                                       The locale for which you want to retrieve localized summaries. Defaults to the primary locale of the marketplace. (optional)
     *
     * @throws \InvalidArgumentException
     */
    public function getCatalogItemAsyncWithHttpInfo(
        string $asin,
        array $marketplace_ids,
        ?array $included_data = null,
        ?string $locale = null,
        ?string $restrictedDataToken = null
    ): PromiseInterface {
        $returnType = '\SpApi\Model\catalogItems\v2022_04_01\Item';
        $request = $this->getCatalogItemRequest($asin, $marketplace_ids, $included_data, $locale);
        if (null !== $restrictedDataToken) {
            $request = RestrictedDataTokenSigner::sign($request, $restrictedDataToken, 'CatalogApi-getCatalogItem');
        } else {
            $request = $this->config->sign($request);
        }
        if ($this->rateLimiterEnabled) {
            $this->getCatalogItemRateLimiter->consume()->ensureAccepted();
        }

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ('\SplFileObject' === $returnType) {
                        $content = $response->getBody(); // stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('string' !== $returnType) {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders(),
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();

                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            )
        ;
    }

    /**
     * Create request for operation 'getCatalogItem'.
     *
     * @param string        $asin
     *                                       The Amazon Standard Identification Number (ASIN) of the item. (required)
     * @param string[]      $marketplace_ids
     *                                       A comma-delimited list of Amazon marketplace identifiers. To find the ID for your marketplace, refer to [Marketplace IDs](https://developer-docs.amazon.com/sp-api/docs/marketplace-ids). (required)
     * @param null|string[] $included_data
     *                                       A comma-delimited list of datasets to include in the response. (optional)
     * @param null|string   $locale
     *                                       The locale for which you want to retrieve localized summaries. Defaults to the primary locale of the marketplace. (optional)
     *
     * @throws \InvalidArgumentException
     */
    public function getCatalogItemRequest(
        string $asin,
        array $marketplace_ids,
        ?array $included_data = null,
        ?string $locale = null
    ): Request {
        // verify the required parameter 'asin' is set
        if (null === $asin || (is_array($asin) && 0 === count($asin))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $asin when calling getCatalogItem'
            );
        }
        // verify the required parameter 'marketplace_ids' is set
        if (null === $marketplace_ids || (is_array($marketplace_ids) && 0 === count($marketplace_ids))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $marketplace_ids when calling getCatalogItem'
            );
        }

        $resourcePath = '/catalog/2022-04-01/items/{asin}';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $marketplace_ids,
            'marketplaceIds', // param base name
            'array', // openApiType
            'form', // style
            false, // explode
            true, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $included_data,
            'includedData', // param base name
            'array', // openApiType
            'form', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $locale,
            'locale', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);

        // path params
        if (null !== $asin) {
            $resourcePath = str_replace(
                '{asin}',
                ObjectSerializer::toPathValue($asin),
                $resourcePath
            );
        }

        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            '',
            $multipart
        );

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem,
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);
            } elseif ('application/json' === $headers['Content-Type']) {
                $httpBody = \GuzzleHttp\json_encode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams, $this->config);
            }
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = ObjectSerializer::buildQuery($queryParams, $this->config);

        return new Request(
            'GET',
            $this->config->getHost().$resourcePath.($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation searchCatalogItems.
     *
     * @param string[]      $marketplace_ids
     *                                           A comma-delimited list of Amazon marketplace identifiers. To find the ID for your marketplace, refer to [Marketplace IDs](https://developer-docs.amazon.com/sp-api/docs/marketplace-ids). (required)
     * @param null|string[] $identifiers
     *                                           A comma-delimited list of product identifiers that you can use to search the Amazon catalog. **Note:** You cannot include &#x60;identifiers&#x60; and &#x60;keywords&#x60; in the same request. (optional)
     * @param null|string   $identifiers_type
     *                                           The type of product identifiers that you can use to search the Amazon catalog. **Note:** &#x60;identifiersType&#x60; is required when &#x60;identifiers&#x60; is in the request. (optional)
     * @param null|string[] $included_data
     *                                           A comma-delimited list of datasets to include in the response. (optional)
     * @param null|string   $locale
     *                                           The locale for which you want to retrieve localized summaries. Defaults to the primary locale of the marketplace. (optional)
     * @param null|string   $seller_id
     *                                           A selling partner identifier, such as a seller account or vendor code. **Note:** Required when &#x60;identifiersType&#x60; is &#x60;SKU&#x60;. (optional)
     * @param null|string[] $keywords
     *                                           A comma-delimited list of keywords that you can use to search the Amazon catalog. **Note:** You cannot include &#x60;keywords&#x60; and &#x60;identifiers&#x60; in the same request. (optional)
     * @param null|string[] $brand_names
     *                                           A comma-delimited list of brand names that you can use to limit the search in queries based on &#x60;keywords&#x60;. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|string[] $classification_ids
     *                                           A comma-delimited list of classification identifiers that you can use to limit the search in queries based on &#x60;keywords&#x60;. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|int      $page_size
     *                                           The number of results to include on each page. (optional, default to 10)
     * @param null|string   $page_token
     *                                           A token that you can use to fetch a specific page when there are multiple pages of results. (optional)
     * @param null|string   $keywords_locale
     *                                           The language of the keywords that are included in queries based on &#x60;keywords&#x60;. Defaults to the primary locale of the marketplace. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|string   $restrictedDataToken Restricted Data Token (RDT) for accessing restricted resources (optional, required for operations that return PII)
     *
     * @throws ApiException              on non-2xx response
     * @throws \InvalidArgumentException
     */
    public function searchCatalogItems(
        array $marketplace_ids,
        ?array $identifiers = null,
        ?string $identifiers_type = null,
        ?array $included_data = null,
        ?string $locale = null,
        ?string $seller_id = null,
        ?array $keywords = null,
        ?array $brand_names = null,
        ?array $classification_ids = null,
        ?int $page_size = 10,
        ?string $page_token = null,
        ?string $keywords_locale = null,
        ?string $restrictedDataToken = null
    ): ItemSearchResults {
        list($response) = $this->searchCatalogItemsWithHttpInfo($marketplace_ids, $identifiers, $identifiers_type, $included_data, $locale, $seller_id, $keywords, $brand_names, $classification_ids, $page_size, $page_token, $keywords_locale, $restrictedDataToken);

        return $response;
    }

    /**
     * Operation searchCatalogItemsWithHttpInfo.
     *
     * @param string[]      $marketplace_ids
     *                                           A comma-delimited list of Amazon marketplace identifiers. To find the ID for your marketplace, refer to [Marketplace IDs](https://developer-docs.amazon.com/sp-api/docs/marketplace-ids). (required)
     * @param null|string[] $identifiers
     *                                           A comma-delimited list of product identifiers that you can use to search the Amazon catalog. **Note:** You cannot include &#x60;identifiers&#x60; and &#x60;keywords&#x60; in the same request. (optional)
     * @param null|string   $identifiers_type
     *                                           The type of product identifiers that you can use to search the Amazon catalog. **Note:** &#x60;identifiersType&#x60; is required when &#x60;identifiers&#x60; is in the request. (optional)
     * @param null|string[] $included_data
     *                                           A comma-delimited list of datasets to include in the response. (optional)
     * @param null|string   $locale
     *                                           The locale for which you want to retrieve localized summaries. Defaults to the primary locale of the marketplace. (optional)
     * @param null|string   $seller_id
     *                                           A selling partner identifier, such as a seller account or vendor code. **Note:** Required when &#x60;identifiersType&#x60; is &#x60;SKU&#x60;. (optional)
     * @param null|string[] $keywords
     *                                           A comma-delimited list of keywords that you can use to search the Amazon catalog. **Note:** You cannot include &#x60;keywords&#x60; and &#x60;identifiers&#x60; in the same request. (optional)
     * @param null|string[] $brand_names
     *                                           A comma-delimited list of brand names that you can use to limit the search in queries based on &#x60;keywords&#x60;. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|string[] $classification_ids
     *                                           A comma-delimited list of classification identifiers that you can use to limit the search in queries based on &#x60;keywords&#x60;. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|int      $page_size
     *                                           The number of results to include on each page. (optional, default to 10)
     * @param null|string   $page_token
     *                                           A token that you can use to fetch a specific page when there are multiple pages of results. (optional)
     * @param null|string   $keywords_locale
     *                                           The language of the keywords that are included in queries based on &#x60;keywords&#x60;. Defaults to the primary locale of the marketplace. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|string   $restrictedDataToken Restricted Data Token (RDT) for accessing restricted resources (optional, required for operations that return PII)
     *
     * @return array of \SpApi\Model\catalogItems\v2022_04_01\ItemSearchResults, HTTP status code, HTTP response headers (array of strings)
     *
     * @throws ApiException              on non-2xx response
     * @throws \InvalidArgumentException
     */
    public function searchCatalogItemsWithHttpInfo(
        array $marketplace_ids,
        ?array $identifiers = null,
        ?string $identifiers_type = null,
        ?array $included_data = null,
        ?string $locale = null,
        ?string $seller_id = null,
        ?array $keywords = null,
        ?array $brand_names = null,
        ?array $classification_ids = null,
        ?int $page_size = 10,
        ?string $page_token = null,
        ?string $keywords_locale = null,
        ?string $restrictedDataToken = null
    ): array {
        $request = $this->searchCatalogItemsRequest($marketplace_ids, $identifiers, $identifiers_type, $included_data, $locale, $seller_id, $keywords, $brand_names, $classification_ids, $page_size, $page_token, $keywords_locale);
        if (null !== $restrictedDataToken) {
            $request = RestrictedDataTokenSigner::sign($request, $restrictedDataToken, 'CatalogApi-searchCatalogItems');
        } else {
            $request = $this->config->sign($request);
        }

        try {
            $options = $this->createHttpClientOption();

            try {
                if ($this->rateLimiterEnabled) {
                    $this->searchCatalogItemsRateLimiter->consume()->ensureAccepted();
                }
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getResponse()->getBody()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }
            if ('\SpApi\Model\catalogItems\v2022_04_01\ItemSearchResults' === '\SplFileObject') {
                $content = $response->getBody(); // stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ('\SpApi\Model\catalogItems\v2022_04_01\ItemSearchResults' !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, '\SpApi\Model\catalogItems\v2022_04_01\ItemSearchResults', []),
                $response->getStatusCode(),
                $response->getHeaders(),
            ];
        } catch (ApiException $e) {
            $data = ObjectSerializer::deserialize(
                $e->getResponseBody(),
                '\SpApi\Model\catalogItems\v2022_04_01\ErrorList',
                $e->getResponseHeaders()
            );
            $e->setResponseObject($data);

            throw $e;
        }
    }

    /**
     * Operation searchCatalogItemsAsync.
     *
     * @param string[]      $marketplace_ids
     *                                          A comma-delimited list of Amazon marketplace identifiers. To find the ID for your marketplace, refer to [Marketplace IDs](https://developer-docs.amazon.com/sp-api/docs/marketplace-ids). (required)
     * @param null|string[] $identifiers
     *                                          A comma-delimited list of product identifiers that you can use to search the Amazon catalog. **Note:** You cannot include &#x60;identifiers&#x60; and &#x60;keywords&#x60; in the same request. (optional)
     * @param null|string   $identifiers_type
     *                                          The type of product identifiers that you can use to search the Amazon catalog. **Note:** &#x60;identifiersType&#x60; is required when &#x60;identifiers&#x60; is in the request. (optional)
     * @param null|string[] $included_data
     *                                          A comma-delimited list of datasets to include in the response. (optional)
     * @param null|string   $locale
     *                                          The locale for which you want to retrieve localized summaries. Defaults to the primary locale of the marketplace. (optional)
     * @param null|string   $seller_id
     *                                          A selling partner identifier, such as a seller account or vendor code. **Note:** Required when &#x60;identifiersType&#x60; is &#x60;SKU&#x60;. (optional)
     * @param null|string[] $keywords
     *                                          A comma-delimited list of keywords that you can use to search the Amazon catalog. **Note:** You cannot include &#x60;keywords&#x60; and &#x60;identifiers&#x60; in the same request. (optional)
     * @param null|string[] $brand_names
     *                                          A comma-delimited list of brand names that you can use to limit the search in queries based on &#x60;keywords&#x60;. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|string[] $classification_ids
     *                                          A comma-delimited list of classification identifiers that you can use to limit the search in queries based on &#x60;keywords&#x60;. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|int      $page_size
     *                                          The number of results to include on each page. (optional, default to 10)
     * @param null|string   $page_token
     *                                          A token that you can use to fetch a specific page when there are multiple pages of results. (optional)
     * @param null|string   $keywords_locale
     *                                          The language of the keywords that are included in queries based on &#x60;keywords&#x60;. Defaults to the primary locale of the marketplace. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     *
     * @throws \InvalidArgumentException
     */
    public function searchCatalogItemsAsync(
        array $marketplace_ids,
        ?array $identifiers = null,
        ?string $identifiers_type = null,
        ?array $included_data = null,
        ?string $locale = null,
        ?string $seller_id = null,
        ?array $keywords = null,
        ?array $brand_names = null,
        ?array $classification_ids = null,
        ?int $page_size = 10,
        ?string $page_token = null,
        ?string $keywords_locale = null
    ): PromiseInterface {
        return $this->searchCatalogItemsAsyncWithHttpInfo($marketplace_ids, $identifiers, $identifiers_type, $included_data, $locale, $seller_id, $keywords, $brand_names, $classification_ids, $page_size, $page_token, $keywords_locale)
            ->then(
                function ($response) {
                    return $response[0];
                }
            )
        ;
    }

    /**
     * Operation searchCatalogItemsAsyncWithHttpInfo.
     *
     * @param string[]      $marketplace_ids
     *                                          A comma-delimited list of Amazon marketplace identifiers. To find the ID for your marketplace, refer to [Marketplace IDs](https://developer-docs.amazon.com/sp-api/docs/marketplace-ids). (required)
     * @param null|string[] $identifiers
     *                                          A comma-delimited list of product identifiers that you can use to search the Amazon catalog. **Note:** You cannot include &#x60;identifiers&#x60; and &#x60;keywords&#x60; in the same request. (optional)
     * @param null|string   $identifiers_type
     *                                          The type of product identifiers that you can use to search the Amazon catalog. **Note:** &#x60;identifiersType&#x60; is required when &#x60;identifiers&#x60; is in the request. (optional)
     * @param null|string[] $included_data
     *                                          A comma-delimited list of datasets to include in the response. (optional)
     * @param null|string   $locale
     *                                          The locale for which you want to retrieve localized summaries. Defaults to the primary locale of the marketplace. (optional)
     * @param null|string   $seller_id
     *                                          A selling partner identifier, such as a seller account or vendor code. **Note:** Required when &#x60;identifiersType&#x60; is &#x60;SKU&#x60;. (optional)
     * @param null|string[] $keywords
     *                                          A comma-delimited list of keywords that you can use to search the Amazon catalog. **Note:** You cannot include &#x60;keywords&#x60; and &#x60;identifiers&#x60; in the same request. (optional)
     * @param null|string[] $brand_names
     *                                          A comma-delimited list of brand names that you can use to limit the search in queries based on &#x60;keywords&#x60;. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|string[] $classification_ids
     *                                          A comma-delimited list of classification identifiers that you can use to limit the search in queries based on &#x60;keywords&#x60;. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|int      $page_size
     *                                          The number of results to include on each page. (optional, default to 10)
     * @param null|string   $page_token
     *                                          A token that you can use to fetch a specific page when there are multiple pages of results. (optional)
     * @param null|string   $keywords_locale
     *                                          The language of the keywords that are included in queries based on &#x60;keywords&#x60;. Defaults to the primary locale of the marketplace. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     *
     * @throws \InvalidArgumentException
     */
    public function searchCatalogItemsAsyncWithHttpInfo(
        array $marketplace_ids,
        ?array $identifiers = null,
        ?string $identifiers_type = null,
        ?array $included_data = null,
        ?string $locale = null,
        ?string $seller_id = null,
        ?array $keywords = null,
        ?array $brand_names = null,
        ?array $classification_ids = null,
        ?int $page_size = 10,
        ?string $page_token = null,
        ?string $keywords_locale = null,
        ?string $restrictedDataToken = null
    ): PromiseInterface {
        $returnType = '\SpApi\Model\catalogItems\v2022_04_01\ItemSearchResults';
        $request = $this->searchCatalogItemsRequest($marketplace_ids, $identifiers, $identifiers_type, $included_data, $locale, $seller_id, $keywords, $brand_names, $classification_ids, $page_size, $page_token, $keywords_locale);
        if (null !== $restrictedDataToken) {
            $request = RestrictedDataTokenSigner::sign($request, $restrictedDataToken, 'CatalogApi-searchCatalogItems');
        } else {
            $request = $this->config->sign($request);
        }
        if ($this->rateLimiterEnabled) {
            $this->searchCatalogItemsRateLimiter->consume()->ensureAccepted();
        }

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    if ('\SplFileObject' === $returnType) {
                        $content = $response->getBody(); // stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('string' !== $returnType) {
                            $content = json_decode($content);
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders(),
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();

                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            )
        ;
    }

    /**
     * Create request for operation 'searchCatalogItems'.
     *
     * @param string[]      $marketplace_ids
     *                                          A comma-delimited list of Amazon marketplace identifiers. To find the ID for your marketplace, refer to [Marketplace IDs](https://developer-docs.amazon.com/sp-api/docs/marketplace-ids). (required)
     * @param null|string[] $identifiers
     *                                          A comma-delimited list of product identifiers that you can use to search the Amazon catalog. **Note:** You cannot include &#x60;identifiers&#x60; and &#x60;keywords&#x60; in the same request. (optional)
     * @param null|string   $identifiers_type
     *                                          The type of product identifiers that you can use to search the Amazon catalog. **Note:** &#x60;identifiersType&#x60; is required when &#x60;identifiers&#x60; is in the request. (optional)
     * @param null|string[] $included_data
     *                                          A comma-delimited list of datasets to include in the response. (optional)
     * @param null|string   $locale
     *                                          The locale for which you want to retrieve localized summaries. Defaults to the primary locale of the marketplace. (optional)
     * @param null|string   $seller_id
     *                                          A selling partner identifier, such as a seller account or vendor code. **Note:** Required when &#x60;identifiersType&#x60; is &#x60;SKU&#x60;. (optional)
     * @param null|string[] $keywords
     *                                          A comma-delimited list of keywords that you can use to search the Amazon catalog. **Note:** You cannot include &#x60;keywords&#x60; and &#x60;identifiers&#x60; in the same request. (optional)
     * @param null|string[] $brand_names
     *                                          A comma-delimited list of brand names that you can use to limit the search in queries based on &#x60;keywords&#x60;. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|string[] $classification_ids
     *                                          A comma-delimited list of classification identifiers that you can use to limit the search in queries based on &#x60;keywords&#x60;. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     * @param null|int      $page_size
     *                                          The number of results to include on each page. (optional, default to 10)
     * @param null|string   $page_token
     *                                          A token that you can use to fetch a specific page when there are multiple pages of results. (optional)
     * @param null|string   $keywords_locale
     *                                          The language of the keywords that are included in queries based on &#x60;keywords&#x60;. Defaults to the primary locale of the marketplace. **Note:** Cannot be used with &#x60;identifiers&#x60;. (optional)
     *
     * @throws \InvalidArgumentException
     */
    public function searchCatalogItemsRequest(
        array $marketplace_ids,
        ?array $identifiers = null,
        ?string $identifiers_type = null,
        ?array $included_data = null,
        ?string $locale = null,
        ?string $seller_id = null,
        ?array $keywords = null,
        ?array $brand_names = null,
        ?array $classification_ids = null,
        ?int $page_size = 10,
        ?string $page_token = null,
        ?string $keywords_locale = null
    ): Request {
        // verify the required parameter 'marketplace_ids' is set
        if (null === $marketplace_ids || (is_array($marketplace_ids) && 0 === count($marketplace_ids))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $marketplace_ids when calling searchCatalogItems'
            );
        }
        if (count($marketplace_ids) > 1) {
            throw new \InvalidArgumentException('invalid value for "$marketplace_ids" when calling CatalogApi.searchCatalogItems, number of items must be less than or equal to 1.');
        }

        if (null !== $identifiers && count($identifiers) > 20) {
            throw new \InvalidArgumentException('invalid value for "$identifiers" when calling CatalogApi.searchCatalogItems, number of items must be less than or equal to 20.');
        }

        if (null !== $keywords && count($keywords) > 20) {
            throw new \InvalidArgumentException('invalid value for "$keywords" when calling CatalogApi.searchCatalogItems, number of items must be less than or equal to 20.');
        }

        if (null !== $page_size && $page_size > 20) {
            throw new \InvalidArgumentException('invalid value for "$page_size" when calling CatalogApi.searchCatalogItems, must be smaller than or equal to 20.');
        }

        $resourcePath = '/catalog/2022-04-01/items';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $identifiers,
            'identifiers', // param base name
            'array', // openApiType
            'form', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $identifiers_type,
            'identifiersType', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $marketplace_ids,
            'marketplaceIds', // param base name
            'array', // openApiType
            'form', // style
            false, // explode
            true, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $included_data,
            'includedData', // param base name
            'array', // openApiType
            'form', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $locale,
            'locale', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $seller_id,
            'sellerId', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $keywords,
            'keywords', // param base name
            'array', // openApiType
            'form', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $brand_names,
            'brandNames', // param base name
            'array', // openApiType
            'form', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $classification_ids,
            'classificationIds', // param base name
            'array', // openApiType
            'form', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $page_size,
            'pageSize', // param base name
            'integer', // openApiType
            '', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $page_token,
            'pageToken', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $keywords_locale,
            'keywordsLocale', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false, // required
            $this->config
        ) ?? []);

        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            '',
            $multipart
        );

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem,
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);
            } elseif ('application/json' === $headers['Content-Type']) {
                $httpBody = \GuzzleHttp\json_encode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams, $this->config);
            }
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = ObjectSerializer::buildQuery($queryParams, $this->config);

        return new Request(
            'GET',
            $this->config->getHost().$resourcePath.($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Create http client option.
     *
     * @return array of http client options
     *
     * @throws \RuntimeException on file opening failure
     */
    protected function createHttpClientOption(): array
    {
        $options = [];
        if ($this->config->getDebug()) {
            $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
            if (!$options[RequestOptions::DEBUG]) {
                throw new \RuntimeException('Failed to open the debug file: '.$this->config->getDebugFile());
            }
        }

        return $options;
    }
}
